package org.xxpay.pay.channel.munion;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.unify.AbstractPaymentConfig;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;

/**
 * @Package org.xxpay.pay.channel.munion
 * @Class: MunionpayPayService.java
 * @Description:
 * @Author leo
 * @Date 2019/4/9 10:14
 * @Version
 **/
@Component
public class MunionpayPaymentService extends BasePayment {
    private final static String logPrefix = "【梦联信息】";
    @Override
    public String getChannelName() {
        return MunionpayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        JSONObject retObj;
        switch (channelId) {
            case MunionpayConfig.CHANNEL_NAME_WXQR:
                retObj = doOrderReq(payOrder);
                break;
            default:
                retObj = buildRetObj(PayConstant.RETURN_VALUE_FAIL, "不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    private JSONObject doOrderReq(PayOrder payOrder) {
        MunionpayConfig munionpayConfig = new MunionpayConfig(getPayParam(payOrder));
        // 请求参数
        Map<String, Object> parameters = Maps.newHashMap();
        parameters.put("userId", munionpayConfig.getMchId());
        parameters.put("sdorderNo", payOrder.getPayOrderId());
        parameters.put("totalFee", payOrder.getAmount());
        parameters.put("gatType", munionpayConfig.getPayMode());
        parameters.put("notifyUrl", payConfig.getNotifyUrl(getChannelName()));
        parameters.put("sign", getSign(munionpayConfig, parameters));
        _log.info("{}请求参数：{}", logPrefix, JSON.toJSONString(parameters));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(getReqUrl(munionpayConfig.getRequestUrl(), MunionpayConfig.REQUEST_CREATE_ORDER),
                parameters, JSONObject.class);
        _log.info("{}同步请求响应参数：{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject retObj = new JSONObject();

        if(StringUtils.equals(origin.getString("code"), MunionpayConfig.RETURN_VALUE_SUCCESS)) {
            JSONObject bizContext = origin.getJSONObject("data");
            // 渠道订单号
            String channelOrderNo = bizContext.getString("orderid");
            // 将订单更改为支付中
            int result = rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), channelOrderNo);
            _log.info("[{}]更新订单状态为支付中:payOrderId={},channelOrderNo={},result={}", getChannelName(), payOrder.getPayOrderId(), channelOrderNo, result);
            // 支付链接地址
            String codeUrl = bizContext.getString("url");
            return buildPayResultOfCodeURL(retObj, payOrder, codeUrl);
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }


    private String getSign(AbstractPaymentConfig config, Map<String, Object> parameters) {
        String signTxt = SignUtils.parameterText(parameters);
        String signValue = SignUtils.MD5.createSign(signTxt, "&key="+config.getPrivateKey(), SignUtils.CHARSET_UTF8);
        return signValue;
    }

    @Override
    public JSONObject query(PayOrder payOrder) {
        MunionpayConfig munionpayConfig = new MunionpayConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        Map<String, Object> parameters = Maps.newHashMap();
        parameters.put("versions", "V1.0");
        parameters.put("character", "UTF-8");
        parameters.put("userId", munionpayConfig.getMchId());
        // 订单类型：orders表示支付订单，payments表示代付订单（梦联暂无代付接口）
        parameters.put("queryType", "orders");
        parameters.put("orderId", payOrderId);
        parameters.put("sign", getSign(munionpayConfig, parameters));

        _log.info("{}订单查询请求参数：{}", logPrefix, JSON.toJSONString(parameters));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(getReqUrl(munionpayConfig.getRequestUrl(), MunionpayConfig.REQUEST_CREATE_ORDER),
                parameters, JSONObject.class);
        _log.info("{}订单查询响应参数：{}", logPrefix, origin.toJSONString());
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("code"), MunionpayConfig.RETURN_VALUE_SUCCESS)) {
            JSONObject bizContext = origin.getJSONObject("data");
            // 梦联订单状态： 0-处理中 1-成功 5-失败
            String status = bizContext.getString("state");
            if(StringUtils.equals("1", status)) {
                retObj.put("status", 2);
            } else {
                retObj.put("status", 1);
            }
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", bizContext.getString("orderid"));
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("msg"));
        return retObj;
    }

}
